package com.news.servlet;

import com.news.model.User;

import com.news.service.UserService;

import com.news.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            User user = userService.login(username, password);
            
            if (user != null) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                
                // 判断是否是管理员
                if ("admin".equals(user.getAdmin())) {
                    // 管理员跳转到后台管理页面
                    session.setAttribute("message", "管理员登录成功！");
//                    session.setAttribute("admin", user);
                    response.sendRedirect("admin/dashboard");
                } else {
                    // 普通用户跳转到首页
                    session.setAttribute("message", "登录成功！");
//                    session.setAttribute("user", user);
                    response.sendRedirect("index");
                }
            } else {
                request.setAttribute("message", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("message", "登录失败：" + e.getMessage());
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // GET请求直接转发到登录页面
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }
} 